import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.*;
import java.util.Locale;


/*
HTTP Response = Status-Line
*(( general-header | response-header | entity-header ) CRLF)
CRLF
[ message-body ]
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/
public class Response implements ServletResponse{

    private static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;


    public Response(OutputStream output) {
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try {
            //File file = new File(HttpServer.WEB_ROOT, request.getUri());
            File file = new File("webroot/" + request.getUri());
            if (file.exists()){
                fis = new FileInputStream(file);

                output.write(Constant.beforeBodyStr.getBytes());
                int len = fis.read(bytes, 0 ,BUFFER_SIZE);
                while (len != -1){
                    output.write(bytes, 0, len);
                    len = fis.read(bytes, 0 ,BUFFER_SIZE);
                }
            } else {
                //file not found
                String errorMsg = "HTTP/1.1 404 File not Found\r\n"
                        + "Content-Type: text/html\r\n"
                        + "Content-Length:23\r\n"
                        + "\r\n"
                        + "<h1>File Not Found</h1>";
                output.write(errorMsg.getBytes());
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (fis != null){
                fis.close();
            }
        }
    }


    public PrintWriter getWriter() throws IOException {
        //autoFlush is true, println() will flush
        //but print() will not
        PrintWriter writer = new PrintWriter(output, true);
        return writer;
    }


    public String getCharacterEncoding() {
        return null;
    }

    public String getContentType() {
        return null;
    }

    public ServletOutputStream getOutputStream() throws IOException {
        return null;
    }

    public void setCharacterEncoding(String s) {

    }

    public void setContentLength(int i) {

    }

    public void setContentType(String s) {

    }

    public void setBufferSize(int i) {

    }

    public int getBufferSize() {
        return 0;
    }

    public void flushBuffer() throws IOException {

    }

    public void resetBuffer() {

    }

    public boolean isCommitted() {
        return false;
    }

    public void reset() {

    }

    public void setLocale(Locale locale) {

    }

    public Locale getLocale() {
        return null;
    }
}
